package com.quan.admin.web.controller;

import com.alibaba.fastjson.JSON;
import com.quan.admin.commons.constant.RabbitMQConstant;
import com.quan.commons.vo.MessageVo;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * WebSocket 前端控制器
 * 提供给前端调用
 * @author yhaoquan
 *
 */
@Slf4j
@RestController
@RequestMapping("/websocket")
public class WebSocketSockJSController extends MyBaseController {
	
	@Autowired
	private SimpMessagingTemplate messagingTemplate ;

	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	/**
	 * 前端SockJS连接，成功返回信息给客户端
	 * @return
	 */
	@SubscribeMapping(value = "/notification")
	public String notification() {
		return "欢迎订阅【系统消息功能】" ;
	}
	
	/**
	 * 广播系统消息
	 * @param message
	 */
	@PostMapping(value = "/toTopicMessage")
	public Object notification(@RequestBody MessageVo message) {
		log.debug("WebSocket广播系统消息：{}", message);
		this.messagingTemplate.convertAndSend("/topic/notification", JSON.toJSONString(message));
		// 发送消息给MQ
		this.rabbitTemplate.convertAndSend(RabbitMQConstant.SYSTEM_EVENT_EXCHANGE, RabbitMQConstant.SYSTEM_ROUTING_KEY_MESSAGE, message);
		return R.ok("消息已发送") ;
	}
	
	/**
	 * 给指定用户发送消息
	 * @param message
	 */
	@PostMapping(value = "/toUserMessage")
	public Object toUser(@RequestBody MessageVo message) {
		log.debug("WebSocket给用户发送消息：{}", message);

		if(null != message.getTo() && !message.getTo().isEmpty()) {
			for (String to : message.getTo()) {
				this.messagingTemplate.convertAndSendToUser(to, "/message", JSON.toJSONString(message));
			}
			// 发送消息给MQ
			this.rabbitTemplate.convertAndSend(RabbitMQConstant.SYSTEM_EVENT_EXCHANGE, RabbitMQConstant.SYSTEM_ROUTING_KEY_MESSAGE, message);

			return R.ok("消息已发送") ;
		} else {
			return R.failure("消息发送失败") ;
		}
	}
	
	
}
